package com.jishuo.nontax.api.socket;

import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Socket 服务启动
 */
@Slf4j
public class SocketServer extends Thread{
	private static Logger logger = LoggerFactory.getLogger(ServerRecvThread.class);

	private static ServerSocket serverSocket = null;

	// 线程池
	private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(20, 20,
			10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

	public void run() {
		try {
			NonTaxConfig nonTaxConfig = (NonTaxConfig) SpringContextUtil.getBean("nonTaxConfig");
			if(serverSocket == null) {
				serverSocket = new ServerSocket(nonTaxConfig.API_Socket_Port);
			}
			log.info("socket服务端开启");
			logger.info("--------socket服务端开启-------");
			while (true){
				Socket socket = serverSocket.accept();
//				System.out.println("接收到客户端socket" + socket.getRemoteSocketAddress());
				threadpool.execute(new ServerRecvThread(socket));
			}
		} catch (IOException e) {
			log.info("socket服务启动异常");
			logger.info("--------socket服务启动异常--------"+e);
			e.printStackTrace();
		}
	}

	public void stopSocket() {
		try {
			if (serverSocket != null) serverSocket.close();
			log.info("socket服务关闭");
		} catch (Exception e) {

		}
	}

}
